import axios from 'axios'
import Element from 'element-ui'
import store from './store'
import router from './router'

axios.defaults.baseURL = 'http://localhost:8081';

//前置拦截
axios.interceptors.request.use(config => {
    console.log("请求url:"+config.url);
    return config
});

axios.interceptors.response.use(response => {
        let res = response.data;
        console.log("===================");
        console.log(res);
        console.log("===================");

        if (res.code === 200) {
            return response;
        } else {
            Element.Message.error('错误消息！',{duration: 3 * 1000});
            return Promise.reject(response.data.msg);
        }
    },
    error => {
        console.log("===================");
        console.log(error);
        console.log("===================");
        if (error.response.data) {
            error.message = error.response.data.msg;
        }
        if (error.response.status === 401) {
            store.commit('REMOVE_INFO');
            router.push({
                path: '/login'
            });
            error.message = '请重新登录';
        }
        if (error.response.status === 403) {
            error.message = '权限不足，无法访问';
        }
        if (error.response.status == 404) {
            error.message = '资源不存在';
        }
        Element.Message({
            message: error.message,
            type: 'error',
            duration: 3 * 1000
        });
        return Promise.reject(error)
    }
)